const { Fruit } = require('../models/fruit');

const Edit = async ctx => {
  let { id, page=1, keyword='' } = ctx.query;
  let err = 0;
  let desc = '';
  let row = null;

  try {
    row = await Fruit.findOne({ where: { id }, raw: true });
    desc = '查询水果成功！';
  } catch (error) {
    desc = '执行出错！';
    err = 10001;
  }

  ctx.render('edit.html',{
    title: '修改水果',
    err,
    desc,
    page,
    keyword,
    row
  });
  
}

const Update = async ctx => {
  let { id, thumb, name, price, page, keyword } = ctx.request.body;
  let err = 0;
  let desc = '';

  try {
    await Fruit.update({ thumb, name, price },{ where: { id } });
    desc = '修改水果成功！';
  } catch (error) {
    desc = '执行出错！';
    err = 10001;
  }

  ctx.render('result.html',{
    err,
    desc,
    page, 
    keyword
  });

}

module.exports = {
  'GET /edit': Edit,
  'POST /update': Update,
}